from Task import Task
from Task import Deadline
import pickle as pickle
import datetime
import os
class TaskManager():
    def __init__(self):
        self.name='default'
        self.save_path = os.path.abspath(os.path.dirname(__file__)) + '/'
        self.tasklist = []
        self.customindex=[]

    def AddTask(self,task):
        self.tasklist.append(task)

    def _TaskCompare(self,mode,Task1,Task2):
        '''
        任务比较
        
        Args:
            mode: 分别有'auto':按紧要、重要但不紧急、紧急但不重要、不紧要排序，相同等级按截止时间从近到远排序
                        'time':按截止时间从近到远排序
                        'importance'：按重要性排序
        Return:
            如果Task1高于Task2，则返回true，否则返回false
        '''
        if (mode=='auto'):
            if (Task1.importance+Task1.emergence == Task2.importance+Task2.emergence):
                if (Task1.importance!=Task2.importance and Task1.emergence!=Task2.emergence):
                    return True if Task1.importance else False
                else:
                    return Task1.deadline<Task2.deadline
            else:
                return Task1.importance+Task1.emergence > Task2.importance+Task2.emergence

        elif (mode=='time'):
            return Task1.deadline<Task2.deadline
        elif (mode=='importance'):
            if (Task1.importance!=Task2.importance):
                return True if Task1.importance else False 
            else:
                return Task1.deadline<Task2.deadline

    def SortTask(self,mode):
        '''
        任务排序
        
        Args:
            mode: 分别有'auto':按紧要、重要但不紧急、紧急但不重要、不紧要排序，相同等级按截止时间从近到远排序
                        'time':按截止时间从近到远排序
                        'importance'：按重要性排序
                        'costom':自定义
        Return:
            None
        '''


        if (mode=='custom'):
            return self.customindex
        else:
            '''
            希尔排序
            '''
            sort_index = [i for i in range(len(self.tasklist))]
            h = 1
            while (h<len(self.tasklist)//3):
                h=3*h+1
            while (h>=1):
                for i in range(h,len(self.tasklist)):
                    for j in range(i,h-1,-h):
                        if (self._TaskCompare(mode,self.tasklist[sort_index[j]],self.tasklist[sort_index[j-h]])):
                            tmp = sort_index[j]
                            sort_index.pop(j)
                            sort_index[j-h:j-h] = [tmp]

                h = h//3
            
            return sort_index

    def Save(self):
        '''
        Save this DataSet as .pkl file.
        
        Args:
            None
        Return:
            None
        '''
        assert self.name != ''
        assert self.save_path != ''
        pickle.dump(self, open(self.save_path + 'TaskManager_' +
                                     self.name + '.pkl', 'wb'), True)
        print('TaskManager ', self.name, ' has benn saved\n')

    def Load(self,name='default'):
        '''
        Load this DataSet with name and path known, which should be given when initialize DataSet class.
        
        Args:
            name: The name of DataSet.
        Return:
            None
        '''
        if name != '':
            self.name = name

        assert self.name != ''
        assert self.save_path != ''
        full_name = self.save_path + 'TaskManager_' + self.name + '.pkl'
        if (os.path.exists(full_name)):
            load_class = pickle.load(open(full_name, 'rb'))
            assert load_class.name == self.name
            assert load_class.save_path == self.save_path
            self.tasklist = load_class.tasklist
            self.customindex = load_class.customindex
            print('TaskManager', self.name, ' has benn load\n')
        else:
            print('file does not exist!')


if __name__ == "__main__":
    # test_data = [
    #     ['a',True,True,[0,0,1,0,0,0,0]],
    #     ['b',False,True,datetime.datetime(2020,9,11)],
    #     ['c',True,False,datetime.datetime(2020,10,4)],
    #     ['d',False,False,[0,1,0,0,0,0,0]],
    #     ['e',True,True,datetime.datetime(2020,9,10)],
    #     ['f',True,True,datetime.datetime(2020,9,15)],
    #     ['g',True,True,datetime.datetime(2020,9,12)],
    #     ['h',True,True,[0,0,0,5,0,0,0]],
    #     ['i',True,True,[0,0,0,8,0,0,0]],
    # ]
    

    # taskmanager = TaskManager()
    # for x in test_data:
    #     taskmanager.AddTask(Task(x[0],x[3],importance=x[1],emergence=x[2]))

    # taskmanager.Save()
    taskmanager = TaskManager()
    taskmanager.Load()

    r_index = taskmanager.SortTask('importance')
    for x in r_index:
        print(taskmanager.tasklist[x].title)